<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="5">
        <el-button
          v-hasPermi="['system:role:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          v-if="true"
          @click="handleAddRules"
          >新增活动</el-button
        >
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="activityList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" width="100" type="index" />
      <el-table-column label="活动名称" prop="title" width="280" />

      <el-table-column label="活动类型" prop="type" width="260">
        <template slot-scope="scope">
          <div>
            {{ scope.row.type == 1 ? "全国" : "区域" }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="活动地区" prop="provinceName" width="400">
        <template slot-scope="scope">
          <div>
            <!-- 去除, -->
            {{ scope.row.provinceName.replace(/,/g, " ") }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="活动时间" prop="created" width="320">
        <template slot-scope="scoped">
          <div>
            {{ getFormateDate(scoped.row.startTime) }}-{{
              getFormateDate(scoped.row.endTime)
            }}
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="单日中奖上限"
        prop="dayMaxRewardCount"
        width="260"
      >
        <template slot-scope="scope">
          <div @click="handleAdd(scope.row)">
            <el-button type="primary">
              {{ scope.row.dayMaxRewardCount }}
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="活动状态" prop="statusDesc" width="260" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="300"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-popconfirm
            confirm-button-text="确认"
            cancel-button-text="取消"
            icon-color="#626AEF"
            title="确定暂停该规则吗"
            @confirm="confirmEvent(scope.row)"
            @cancel="cancelEvent"
          >
            <template #reference>
              <el-button
                v-if="scope.row.status == 0"
                size="mini"
                type="text"
                icon="el-icon-lock"
                @click="handlePause()"
                >暂停</el-button
              >
            </template>
          </el-popconfirm>
          <el-button
            v-if="scope.row.status == 1"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleOpen(scope.row.activityId)"
            >启动</el-button
          >

          <el-button
            v-if="1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row.activityId)"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="tableParams.pageNum"
      :limit.sync="tableParams.pageSize"
      @pagination="getList"
    />
    <!-- 上限弹出窗口 -->
    <el-dialog
      v-model="ruleshow"
      :title="title"
      width="600px"
      append-to-body
      :visible.sync="open"
    >
      <div class="setting-number">
        <p>单日中奖上限：</p>
        <el-input
          v-model="dayMaxRewardCount"
          placeholder="单日中奖上限,无上限"
          clearable
          style="margin-left: 20px"
          class="setting-input"
          type="number"
          min="0"
        />
      </div>
      <div class="dialog-footer" slot="footer">
        <el-button @click="cancelSetting">返回</el-button>
        <el-button type="primary" @click="confirmSetting">保存</el-button>
      </div>
    </el-dialog>

    <!-- 新增活动弹窗 -->
    <el-dialog
      v-model="addActivityshow"
      :title="addActivityTitle"
      width="1200px"
      append-to-body
      :visible.sync="openAddctivity"
      @close="cancelAddActivitySetting"
    >
      <!-- 新增活动详情 -->
      <el-form
        :model="activityForm"
        label-width="auto"
        style="max-width: 1100px"
      >
        <el-form-item label="活动名称">
          <el-input v-model="activityForm.title" />
        </el-form-item>
        <el-form-item label="活动地区">
          <el-select
            v-model="activityForm.provinceId"
            placeholder="选择省份"
            clearable
            @clear="clearProvice"
            multiple
          >
            <el-option
              v-for="dict in countryList"
              :key="dict.code"
              :label="dict.name"
              :value="dict.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间">
          <el-date-picker
            style="margin-left: 20px"
            v-model="activityForm.createdTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            disabled
          />
        </el-form-item>
      </el-form>

      <!-- 规则表格 -->
      <!-- 新增规则 -->
      <el-button @click="addActivityRule">新增规则</el-button>
      <el-table :data="activityForm.rewardRuleGroupVoList" style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-table :data="scope.row.rewardList" style="width: 100%">
              <el-table-column prop="hnRewardId" label="奖品id" width="100">
              </el-table-column>
              <el-table-column prop="title" label="奖品名称" width="200">
              </el-table-column>
              <el-table-column
                prop="prob"
                label="奖品概率（千万份）"
                width="200"
              >
              </el-table-column>
              <el-table-column prop="max" label="库存" width="200">
              </el-table-column>
            </el-table>
            <!-- type 2大奖 -->
            <div v-if="scope.row.type == 2">
              <div
                class="first-reward"
                v-for="item in rewardForm.rewardList"
                :key="item.rewardId"
              >
                <div class="reward-left">
                  <div style="display: flex; width: 100%">
                    <p class="left-title">奖品名称</p>
                    <p class="left-title">奖品数量</p>
                    <p class="left-title" style="opacity: 0">库存</p>
                  </div>
                  <div class="reward-info">
                    <el-input
                      v-model="item.title"
                      placeholder="奖品名称"
                      clearable
                      class="input"
                      disabled
                    />
                    <el-input
                      v-model="item.bigRewardDemandJson.bigRewardCount"
                      placeholder="奖品数量"
                      clearable
                      class="input"
                      disabled
                    />
                    <el-input
                      style="opacity: 0"
                      v-model="item.max"
                      placeholder="库存"
                      clearable
                      class="input"
                    />
                  </div>
                </div>
                <div class="reward-right">
                  <p>参与条件</p>
                  <div class="reward-right-number">
                    <p>抽奖次数</p>
                    <el-input
                      v-model="item.bigRewardDemandJson.smallDrawTime"
                      placeholder="奖品数量1"
                      clearable
                      class="number-input"
                      disabled
                      type="number"
                    />
                    ~<el-input
                      v-model="item.bigRewardDemandJson.bigDrawTime"
                      placeholder="奖品数量2"
                      clearable
                      class="number-input"
                      disabled
                      type="number"
                    />
                    <el-popconfirm
                      confirm-button-text="确认"
                      cancel-button-text="取消"
                      icon-color="#626AEF"
                      title="确定要暂停该活动规则吗？暂停该活动规则后，将取消该投放计划！"
                      @confirm="cancelBigReward(item.rewardId)"
                      @cancel="cancelPopconfirm"
                      v-if="item.status == 1"
                    >
                      <template #reference>
                        <el-button
                          type="danger"
                          style="margin-left: 20px"
                          v-if="
                            item.status == 1 &&
                            item.bigRewardDemandJson.beginTimestamp >
                              new Date().getTime()
                          "
                        >
                          取消</el-button
                        >
                      </template>
                    </el-popconfirm>
                  </div>
                  <div class="reward-right-time">
                    <p>投放时间</p>
                    <el-date-picker
                      style="margin-left: 20px"
                      :value="[
                        new Date(item.bigRewardDemandJson.beginTimestamp),
                        new Date(item.bigRewardDemandJson.endTimestamp),
                      ]"
                      disabled
                      type="datetimerange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="yyyy-MM-dd"
                    />
                  </div>
                  <div class="reward-right-time">
                    <p>投放地区</p>
                    <p>{{ item.districtName }}</p>
                    <el-select
                      v-model="item.bigRewardDemandJson.provinceId"
                      placeholder="活动地区"
                      clearable
                      style="margin-left: 20px"
                      v-if="newRewardForm.length != 0"
                      multiple
                      disabled
                    >
                      <el-option
                        v-for="dict in countryList"
                        :key="dict.code"
                        :label="dict.name"
                        :value="dict.code"
                        disabled
                      />
                    </el-select>
                    <el-select
                      v-model="item.bigRewardDemandJson.cityId"
                      placeholder="活动地区"
                      clearable
                      style="margin-left: 20px"
                      v-if="newRewardForm.length != 0"
                      multiple
                      disabled
                    >
                      <el-option
                        v-for="dict in cityList"
                        :key="dict.code"
                        :label="dict.name"
                        :value="dict.code"
                        disabled
                      />
                    </el-select>
                    <el-select
                      v-model="item.bigRewardDemandJson.areaId"
                      placeholder="活动地区"
                      clearable
                      style="margin-left: 20px"
                      v-if="newRewardForm.length != 0"
                      multiple
                      disabled
                    >
                      <el-option
                        v-for="dict in countryList"
                        :key="dict.code"
                        :label="dict.name"
                        :value="dict.code"
                        disabled
                      />
                    </el-select>
                    <!-- <div v-else style="margin-left: 40px">全国</div> -->
                  </div>
                </div>
              </div>
            </div>

            <el-button
              type="warning"
              v-if="scope.row.type == 2 && false"
              @click="addReallyReward(purchaseEditForm.activityId)"
              >添加实物奖品</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="groupName" label="规则名称" width="200">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.groupName"
              :disabled="scope.row.type != 1"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="top" label="规则明细" width="350">
          <template slot-scope="scope">
            <div v-if="scope.row.ruleJson">
              <!-- <p>城市id:{{ scope.row.ruleJson.cityId }}</p> -->
              <!-- <p>区域id:{{ scope.row.ruleJson.areaId }}</p> -->
              <!-- <p>
                起止时间:{{ scope.row.ruleJson.beginTimestamp }}-{{
                  scope.row.ruleJson.endTimestamp
                }}
              </p> -->
              <p style="display: flex">
                抽奖次数:
                <el-select
                  v-model="scope.row.ruleJson.selectCount"
                  placeholder="选择抽奖次数"
                  clearable
                >
                  <el-option
                    v-for="dict in countList"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </p>
            </div>
            <div v-else>暂无</div>
          </template>
        </el-table-column>
        <el-table-column prop="max" label="奖品" width="350">
          <template slot-scope="scope">
            <!-- <div v-if="scope.row.type == 1">
              <el-select
                v-model="scope.row.selectRewarded"
                placeholder="选择奖品"
                clearable
                multiple
              >
                <el-option
                  v-for="dict in selectRewardList"
                  :key="dict.hnRewardId"
                  :label="dict.title"
                  :value="dict.hnRewardId"
                />
              </el-select>
            </div> -->
            <div v-for="item in scope.row.rewardList" :key="item.rewardId">
              {{ item.title }}
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="status" label="规则状态" width="250">
          <template slot-scope="scope">
            <div v-if="scope.row.status">
              {{ scope.row.status == 1 ? "正常" : "暂停" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="规则类型" width="250">
        </el-table-column> -->
      </el-table>

      <div class="dialog-footer" slot="footer" style="margin-top: 40px">
        <el-button @click="cancelAddActivitySetting">返回</el-button>
        <el-button type="primary" @click="confirmAddActivitySetting"
          >保存活动</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getActivityReward,
  updateActivityRewardStatus,
  updateDayMaxRewardCount,
  addActivity,
  getRewardRuleDrawTime,
  getAddressList,
} from "@/api/lottery/index";
import { getRewardLists } from "@/api/record/index";
export default {
  name: "Role",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //   是否弹出层
      open: false,
      open1: false,
      openAddctivity: false,
      // 表格数据
      activityList: [],
      // 弹窗展示
      ruleshow: false,
      addActivityshow: false,
      addActivityTitle: "",
      // 添加活动的form
      activityForm: {
        title: "",
        provinceId: "",
        startTime: "1704038400000",
        endTime: "1735660799000",
        createdTime: [new Date(1704038400000), new Date(1735660799000)],
        rewardRuleGroupVoList: [
          {
            groupName: "基础规则组1",
            type: 0,
            rewardList: [
              {
                hnRewardId: "1",
                type: 0,
                title: "谢谢参与",
                num: 0,
                prob: 7500004,
                max: 0,
              },
              {
                hnRewardId: "2",
                type: 2,
                title: "29元红包",
                num: 2900,
                prob: 4145,
                max: 300000,
              },
              {
                hnRewardId: "3",
                type: 2,
                title: "2.9元红包",
                num: 290,
                prob: 276395,
                max: 20000000,
              },
              {
                hnRewardId: "4",
                type: 2,
                title: "0.5元红包",
                num: 50,
                prob: 2219456,
                max: 160599900,
              },
            ],
          },
          {
            groupName: "基础大奖",
            type: 2,
            // ruleJson: {
            //   smallDrawRewardCount: "",
            //   bigDrawRewardCount: "",
            //   selectCount: "",
            // },
            selectRewarded: "",
            rewardList: [],
          },
        ],
      },
      // 规则类型字典
      ruleTypeDict: [
        {
          label: "首次抽奖",
          value: "RewardRuleFirstDrawStrategy",
        },
        {
          label: "N次必中",
          value: "RewardRuleTimesHitStrategy",
        },
      ],
      // 规则字典选中
      ruleType: "RewardRuleFirstDrawStrategy",
      // 城市列表
      countryList: [],
      // 次数列表
      countList: [],
      // 奖品列表
      selectRewardList: [],
      // 新增弹窗表格
      purchaseAddForm: {},
      // 奖品列表
      rewardList: [],
      tableData: [],
      // 大奖表单
      rewardForm: [],
      //   标题
      title: "",
      // 表单查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activetyName: "",
        isScan: "",
        address: "",
        time: "",
        reward: "",
        isLimit: "",
        status: "",
      },

      // 表单校验
      rules: {},
      // 表格分页数据
      tableParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 中奖上限
      dayMaxRewardCount: "",
      // 当前选择的活动id
      activityId: 0,
    };
  },
  created() {
    this.getList();
    this.getProvinceCityArea({
      parentId: "",
    });
    this.getRewardRuleCount();
    this.getSelectRewardList();
  },
  methods: {
    getList() {
      getActivityReward().then((res) => {
        this.activityList = res.data.records;
        this.loading = false;
        this.total = res.data.total;
      });
    },
    // 获取全国省
    getProvinceCityArea(params) {
      getAddressList(params).then((res) => {
        if (res.code == 0) {
          this.countryList = res.data.map((it) => {
            return {
              code: it.districtId,
              name: it.name,
            };
          });
        }
      });
    },
    // 获取抽奖次数列表
    getRewardRuleCount() {
      getRewardRuleDrawTime().then((res) => {
        if (res.code == 0) {
          this.countList = res.data.map((it) => {
            return {
              value: it,
              label: it.replace("_", ","),
            };
          });
        }
      });
    },
    // 获取奖品列表
    getSelectRewardList() {
      getRewardLists().then((res) => {
        if (res.code == 0) {
          this.selectRewardList = res.data;
        }
      });
    },
    handleQuery() {},
    resetQuery() {},
    handleSelectionChange() {},
    handleAdd(row) {
      this.open = true;
      this.ruleshow = true;
      this.title = row.title;
      this.activityId = row.activityId;
    },
    handleEdit(id) {
      this.$router.push("/lottery/add?id=" + id);
    },
    handlePause() {},
    confirmEvent(item) {
      let params = {
        activityId: item.activityId,
        status: 1,
      };
      updateActivityRewardStatus(params).then((res) => {
        if (res.code == 0) {
          this.$message.success("暂停成功");
          this.getList();
        }
      });
    },
    getFormateDate(date) {
      let year = new Date(date).getFullYear();
      let month = new Date(date).getMonth() + 1;
      let day = new Date(date).getDate();
      let hour = new Date(date).getHours();
      let min = new Date(date).getMinutes();
      let seconds = new Date(date).getSeconds();

      // 确保月份、小时、分钟和秒都是两位数的格式
      month = month.toString().padStart(2, "0");
      hour = hour.toString().padStart(2, "0");
      day = day.toString().padStart(2, "0");
      min = min.toString().padStart(2, "0");
      seconds = seconds.toString().padStart(2, "0");

      return `${year}-${month}-${day} ${hour}:${min}:${seconds}`;
    },
    cancelEvent() {},
    handleOpen(id) {
      // 启动0 暂停1
      updateActivityRewardStatus({
        activityId: id,
        status: 0,
      }).then((res) => {
        this.$message.success("启动成功");
        this.getList();
      });
    },
    confirmSetting() {
      console.log(this.activityId, this.dayMaxRewardCount);
      updateDayMaxRewardCount({
        activityId: this.activityId,
        dayMaxRewardCount: this.dayMaxRewardCount,
      }).then((res) => {
        if (res.code == 0) {
          this.$message.success("设置成功");
          this.cancelSetting();
          this.getList();
        }
      });
    },
    cancelSetting() {
      this.activityId = null;
      this.dayMaxRewardCount = "";
      this.ruleshow = false;
      this.open = false;
    },
    // 添加活动
    handleAddRules() {
      this.openAddctivity = true;
      this.addActivityTitle = "添加活动";
      this.addActivityshow = true;
    },
    // 确认添加
    confirmAddActivitySetting() {
      if (this.activityForm.title == "") {
        this.$message.error("请输入活动名称");
        return;
      }
      if (this.activityForm.createdTime == "") {
        this.$message.error("请选择起止时间");
        return;
      }
      if (this.activityForm.provinceId == "") {
        this.$message.error("请选择省");
        return;
      }
      let params = {
        startTime: new Date(this.activityForm.createdTime[0]).getTime(),
        endTime: new Date(this.activityForm.createdTime[1]).getTime(),
        provinceId: this.activityForm.provinceId.join(","),
        title: this.activityForm.title,
        rewardRuleGroupVoList: this.activityForm.rewardRuleGroupVoList,
      };

      params.rewardRuleGroupVoList.forEach((item) => {
        if (item.type == 1) {
          // 选择部分奖品逻辑
          // item的rewardlist带上 selectRewarded里面的hnRewardId 与奖品列表相同的奖品列表项
          // item.selectRewarded.forEach((item2) => {
          //   this.selectRewardList.forEach((item3) => {
          //     if (item2 == item3.hnRewardId) {
          //       item.rewardList.push(item3);
          //     }
          //   });
          // });
          // 同时 item里面的ruleJson的nsmallDrawRewardCount,bigDrawRewardCount,为selectCount的0 1项
          item.ruleJson.smallDrawRewardCount =
            item.ruleJson.selectCount.split("_")[0];
          item.ruleJson.bigDrawRewardCount =
            item.ruleJson.selectCount.split("_")[1];
        }
      });
      console.log(params);

      addActivity(params).then((res) => {
        if (res.code == 0) {
          this.$message.success("添加活动成功");
          this.cancelAddActivitySetting();
          this.getList();
        }
      });
    },
    // 取消活动
    cancelAddActivitySetting() {
      this.openAddctivity = false;
      this.addActivityTitle = "";
      this.addActivityshow = false;
      this.activityForm = {
        title: "",
        provinceId: "",
        startTime: "1704038400000",
        endTime: "1735660799000",
        createdTime: [new Date(1704038400000), new Date(1735660799000)],
        rewardRuleGroupVoList: [
          {
            groupName: "基础规则组1",
            type: 0,
            rewardList: [
              {
                hnRewardId: "1",
                type: 0,
                title: "谢谢参与",
                num: 0,
                prob: 7500004,
                max: 0,
              },
              {
                hnRewardId: "2",
                type: 2,
                title: "29元红包",
                num: 2900,
                prob: 4145,
                max: 300000,
              },
              {
                hnRewardId: "3",
                type: 2,
                title: "2.9元红包",
                num: 290,
                prob: 276395,
                max: 20000000,
              },
              {
                hnRewardId: "4",
                type: 2,
                title: "0.5元红包",
                num: 50,
                prob: 2219456,
                max: 160599900,
              },
            ],
          },
          {
            groupName: "基础大奖",
            type: 2,
            // ruleJson: {
            //   smallDrawRewardCount: "",
            //   bigDrawRewardCount: "",
            //   selectCount: "",
            // },
            selectRewarded: "",
            rewardList: [],
          },
        ],
      };
    },
    // 新增活动下规则
    addActivityRule() {
      this.activityForm.rewardRuleGroupVoList.push({
        groupName: "",
        type: 1,
        ruleJson: {
          smallDrawRewardCount: "",
          bigDrawRewardCount: "",
          selectCount: "",
          strategy:"RewardRuleFirstDrawStrategy",
        },
        selectRewarded: "",
        rewardList: [
          {
            hnRewardId: "1",
            type: 0,
            title: "谢谢参与",
            num: 0,
            prob: 7500004,
            max: 0,
          },
          {
            hnRewardId: "2",
            type: 2,
            title: "29元红包",
            num: 2900,
            prob: 4145,
            max: 300000,
          },
          {
            hnRewardId: "3",
            type: 2,
            title: "2.9元红包",
            num: 290,
            prob: 276395,
            max: 20000000,
          },
          {
            hnRewardId: "4",
            type: 2,
            title: "0.5元红包",
            num: 50,
            prob: 2219456,
            max: 160599900,
          },
        ],
      });
    },
    // 新增规则的选择抽奖次数
    changeCount(e) {
      // this.activityForm;
    },
    // 清空省
    clearProvice() {
      this.activityForm.provinceId = "";
    },
  },
};
</script>

<style scoped lang="scss">
.setting-number {
  p {
    width: 120px;
  }
  .setting-input {
    width: 260px;
  }
  margin-top: 20px;
  display: flex;
  align-items: center;
}
</style>
